﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

namespace Adams.Public.Api
{
    public class JsonXmlResult : ActionResult
    {
        private static UTF8Encoding UTF8 = new UTF8Encoding(false);

        public object Data { get; set; }

        public JsonXmlResult(object data)
        {
            this.Data = data;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            bool hasContentType = string.IsNullOrEmpty(context.HttpContext.Request.Headers["Accept"]) ? false : true;
            bool hasFormatParam = string.IsNullOrEmpty(context.HttpContext.Request["format"]) ? false : true;
            bool isJson = false;

            if(hasContentType)
            {
                isJson = context.HttpContext.Request.Headers["Accept"].Contains("json");
            }

            if (hasFormatParam)
            {
                isJson = isJson || context.HttpContext.Request["format"].Contains("json");
            }

            if (isJson)
            {
                new JsonResult { Data = this.Data, JsonRequestBehavior = JsonRequestBehavior.AllowGet }.ExecuteResult(context);
            }
            else
            {
                new ContentResult { 
                    ContentType = "text/xml", 
                    Content = Adams.Shared.Serialize.SerializeXml(this.Data), 
                    ContentEncoding = UTF8 }.ExecuteResult(context);
            }
        }
    }
}